const fs = require('fs')
const path = require('path')
const http = require('http')
const readline = require('readline');

function mkdirsSync(dirname) {
	if (fs.existsSync(dirname)) {
		return true
	} else {
		if (mkdirsSync(path.dirname(dirname))) {
			fs.mkdirSync(dirname)
			return true
		}
	}
}

function getPath(pathUrl) {
	return path.resolve(__dirname, pathUrl)
}

function generateTemplate(arr) {
	return `import request from '@/utils/request'`
}

function generateFunc(name, summary, type, singleParameter) {
	const arr = name.slice(1).split('/')
	const fun = arr[arr.length - 1]
	if(type == 'get'){
		return `
// ${summary || ''} 
export function ${fun}(params) { 
	return request({ 
		url: '${name}', 
		method: '${type}', 
		params: params 
	})
}
`
	}else if(type == 'post' || type == 'put'){
		if(singleParameter){
			return `
// ${summary || ''} 
export function ${fun}(id) { 
	return request({ 
		url: '${name}?${singleParameter}=' + id, 
		method: '${type}'
	})
}
`
		}else{
			return `
// ${summary || ''} 
export function ${fun}(data) { 
	return request({ 
		url: '${name}', 
		method: '${type}', 
		data: data 
	})
}
			`
		}
		
	}else if(type == 'delete'){
		return `
// ${summary || ''} 
export function ${fun}(id) { 
	return request({ 
		url: '${name}?id=' + id, 
		method: '${type}'
	})
}
`
	}
}

function httpgetJson(optinos) {
	return new Promise((resolve, reject) => {
		http.get(optinos, (res) => {
			const { statusCode } = res
			const contentType = res.headers['content-type']

			let error
			if (statusCode !== 200) {
				error = new Error('请求失败。 ' + `状态码: ${statusCode}`)
				res.on('end', () => { resolve(statusCode) })
			} 
			if (error) {
				console.error(error.message)
				// 消耗响应数据以释放内存
				res.resume()
				return
			}
			res.setEncoding('utf8')
			let rawData = ''
			res.on('data', (chunk) => {
				rawData += chunk
			})
			res.on('end', () => {
				try {
					const parsedData = JSON.parse(rawData)
					resolve(parsedData)
				} catch (e) {
					reject(`错误: ${e.message}`)
				}
			})
		}).on('error', (e) => {
			reject(`错误: ${e.message}`)
		})
	})
}

const srcFolder = '/src'
//后台管理端接口
const adminUrlList = ['Admin', 'AccountAdmin', 'PluginAdmin']
//小程序端接口
const apiUrlList = ['Api', 'AccountApi', 'PluginApi']
//域名或IP地址
const IPaddress = null

//读取解析用户输入的域名或IP
function readSyncByRl(tips) {
    tips = tips || '> ';
    return new Promise((resolve) => {
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
 
        rl.question(tips, (answer) => {
            rl.close();
            resolve(answer.trim());
        });
    });
}

//读取用户选择的数据端
function dataEnd(tips) {
    tips = tips || '> ';
    return new Promise((resolve) => {
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
 
        rl.question(tips, (answer) => {
            rl.close();
            resolve(answer.trim());
        });
    });
}

async function main() {
	const IPaddress = await readSyncByRl('请输入接口域名或IP地址：')
	const PCorAND = await readSyncByRl('请选择获取的数据端(y:Admin/n:Android)：')
	let ends 
	if(['Y', 'y', 'YES', 'yes'].indexOf(PCorAND) > -1){
		ends = adminUrlList
	}else if(['N', 'n', 'NO', 'no'].indexOf(PCorAND) > -1){
		ends = apiUrlList
	}else{
		console.log('选择有误，已退出程序！')
		return
	}
	for(let i = 0; i < ends.length; i++){
		console.log('获取远程json文件中...')
		const urlAddress = IPaddress + '/swagger/' + ends[i] + '/swagger.json'
		console.log(urlAddress);
		const result = await httpgetJson(urlAddress)
		if(result.paths == 404) continue
		console.log('获取成功正在生成api文件')
		const obj = {}
		// let paths = result.paths
		for (const name in result.paths) {
			const path = result.paths[name]
			let folder = ''
			if (path.post) {
				const tag = path.post.tags[0]
				if (!tag) continue
				const urlArray = name.slice(1).split('/')
				if (urlArray.length === 4) {
					folder = urlArray[1]
				} else {
					if ((ends == adminUrlList && urlArray[0] !== tag) || (ends == apiUrlList && urlArray[1] !== tag)) continue
				}
				if (obj[path.post.tags[0]]) {
					obj[path.post.tags[0]].push({
						summary: path.post.summary,
						tag,
						name,
						type: 'post',
						folder,
						singleParameter: false
					})
				} else {
					obj[path.post.tags[0]] = [{
						summary: path.post.summary,
						tag,
						name,
						type: 'post',
						folder,
						singleParameter: false
					}]
				}
			} else if (path.get) {
				const tag = path.get.tags[0]
				if (!tag) continue
				const urlArray = name.slice(1).split('/')
				if (urlArray.length === 4) {
					folder = urlArray[1]
				} else {
					if ((ends == adminUrlList && urlArray[0] !== tag) || (ends == apiUrlList && urlArray[1] !== tag)) continue
				}
				if (obj[path.get.tags[0]]) {
					obj[path.get.tags[0]].push({
						summary: path.get.summary,
						tag,
						name,
						type: 'get',
						folder,
						singleParameter: false
					})
				} else {
					obj[path.get.tags[0]] = [{
						summary: path.get.summary,
						tag,
						name,
						type: 'get',
						folder,
						singleParameter: false
					}]
				}
			} else if (path.put) {
				const tag = path.put.tags[0]
				if (!tag) continue
				const urlArray = name.slice(1).split('/')
				if (urlArray.length === 4) {
					folder = urlArray[1]
				} else {
					if ((ends == adminUrlList && urlArray[0] !== tag) || (ends == apiUrlList && urlArray[1] !== tag)) continue
				}
				if (obj[path.put.tags[0]]) {
					obj[path.put.tags[0]].push({
						summary: path.put.summary,
						tag,
						name,
						type: 'put',
						folder,
						singleParameter: path.put.parameters ? path.put.parameters[0].name : false
					})
				} else {
					obj[path.put.tags[0]] = [{
						summary: path.put.summary,
						tag,
						name,
						type: 'put',
						folder,
						singleParameter: path.put.parameters ? path.put.parameters[0].name : false
					}]
				}
			} else if (path.delete) {
				const tag = path.delete.tags[0]
				if (!tag) continue
				const urlArray = name.slice(1).split('/')
				if (urlArray.length === 4) {
					folder = urlArray[1]
				} else {
					if ((ends == adminUrlList && urlArray[0] !== tag) || (ends == apiUrlList && urlArray[1] !== tag)) continue
				}
				if (obj[path.delete.tags[0]]) {
					obj[path.delete.tags[0]].push({
						summary: path.delete.summary,
						tag,
						name,
						type: 'delete',
						folder,
						singleParameter: false
					})
				} else {
					obj[path.delete.tags[0]] = [{
						summary: path.delete.summary,
						tag,
						name,
						type: 'delete',
						folder,
						singleParameter: false
					}]
				}
			}
		}
		for (const tagName in obj) {
			let jsString = ''
			const requestTypes = []
			let folder = ''
			for (const item of obj[tagName]) {
				const requestType = requestTypes.filter(o => o === item.type)
				if (requestType.length === 0) requestTypes.push(item.type)
				jsString += generateFunc(item.name, item.summary, item.type, item.singleParameter)
				folder = item.folder
			}
			jsString = generateTemplate(requestTypes) + jsString
			mkdirsSync(getPath(`..${srcFolder}/api/${folder}`))
			fs.writeFileSync(getPath(`..${srcFolder}/api/${folder}/${tagName}.js`), jsString)
		}
	}
	console.log('生成完毕')
}

main()
